<?php

//获得当前的脚本网址
function GetCurUrl(){
	if(!empty($_SERVER["REQUEST_URI"])){
		$scriptName = $_SERVER["REQUEST_URI"];
		$nowurl = $scriptName;
	}else{
		$scriptName = $_SERVER["PHP_SELF"];
		if(empty($_SERVER["QUERY_STRING"])){
			$nowurl = $scriptName;
		}else{
			$nowurl = $scriptName."?".$_SERVER["QUERY_STRING"];
		}
	}
	return $nowurl;
}

//兼容php4
if(!function_exists('file_put_contents')){
	function file_put_contents($n,$d){
		$f=@fopen($n,"w");
		if (!$f){
			return false;
		}else{
			fwrite($f,$d);
			fclose($f);
			return true;
		}
	}
}

//utf-8中文截取，单字节截取模式
function cn_substr_utf8($str, $length, $start=0){
	if(strlen($str) < $start+1){
		return '';
	}
	preg_match_all("/./su", $str, $ar);
	$str = '';
	$tstr = '';
	//为了兼容mysql4.1以下版本,与数据库varchar一致,这里使用按字节截取
	for($i=0; isset($ar[0][$i]); $i++){
		if(strlen($tstr) < $start){
			$tstr .= $ar[0][$i];
		}else{
			if(strlen($str) < $length + strlen($ar[0][$i]) ){
				$str .= $ar[0][$i];
			}else{
				break;
			}
		}
	}
	return $str;
}

function GetIP(){
	if(!empty($_SERVER["HTTP_CLIENT_IP"])){
		$cip = $_SERVER["HTTP_CLIENT_IP"];
	}else if(!empty($_SERVER["HTTP_X_FORWARDED_FOR"])){
		$cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
	}else if(!empty($_SERVER["REMOTE_ADDR"])){
		$cip = $_SERVER["REMOTE_ADDR"];
	}else{
		$cip = '';
	}
	preg_match("/[\d\.]{7,15}/", $cip, $cips);
	$cip = isset($cips[0]) ? $cips[0] : 'unknown';
	unset($cips);
	return $cip;
}
//缩图片自动生成函数，来源支持bmp、gif、jpg、png
//但生成的小图只用jpg或png格式
function ImageResize($srcFile,$toW,$toH,$toFile="")
{
	if($toFile==""){
		$toFile = $srcFile;
	}
	$info = "";
	$srcInfo = GetImageSize($srcFile,$info);
	switch ($srcInfo[2]){
		case 1:
			$im = imagecreatefromgif($srcFile);
			break;
		case 2:
			$im = imagecreatefromjpeg($srcFile);
			break;
		case 3:
			$im = imagecreatefrompng($srcFile);
			break;
		case 6:
			$im = imagecreatefromwbmp($srcFile);
			break;
	}
	$srcW=ImageSX($im);
	$srcH=ImageSY($im);
	if($srcW<=$toW && $srcH<=$toH ){
		return true;
	}
	$toWH=$toW/$toH;
	$srcWH=$srcW/$srcH;
	if($toWH<=$srcWH){
		$ftoW=$toW;
		$ftoH=$ftoW*($srcH/$srcW);
	}else{
		$ftoH=$toH;
		$ftoW=$ftoH*($srcW/$srcH);
	}
	if($srcW>$toW||$srcH>$toH){
		if(function_exists("imagecreatetruecolor")){
			@$ni = imagecreatetruecolor($ftoW,$ftoH);
			if($ni){
				imagecopyresampled($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
			}else{
				$ni=imagecreate($ftoW,$ftoH);
				imagecopyresized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
			}
		}else{
			$ni=imagecreate($ftoW,$ftoH);
			imagecopyresized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
		}
		switch ($srcInfo[2]){
			case 1:
				imagegif($ni,$toFile);
				break;
			case 2:
				imagejpeg($ni,$toFile,85);
				break;
			case 3:
				imagepng($ni,$toFile);
				break;
			case 6:
				imagebmp($ni,$toFile);
				break;
			default:
				return false;
		}
		imagedestroy($ni);
	}
	imagedestroy($im);
	return true;
}


//将HTML原义输出
function unhtml ($content){
	$content = htmlspecialchars($content);
	$content = str_replace(chr(13), '<br>', $content);
	$content = str_replace(chr(32), '&nbsp', $content);
	return trim($content);
}

function RmDirFiles($indir){
		if(!is_dir($indir)){
			return ;
		}
		$dh = dir($indir);
		while($filename = $dh->read()){
			if($filename == "." || $filename == ".."){
				continue;
			}else if(is_file("$indir/$filename")){
				@unlink("$indir/$filename");
			}else{
				RmDirFiles("$indir/$filename");
			}
		}
		$dh->close();
		rmdir($indir);
}
/**
 * 删除特定名字目录
 *
 * @param unknown_type $indir
 */
function rmdirsvn($indir){
	if(!is_dir($indir)){
		return ;
	}
	$dh = dir($indir);
	while($filename = $dh->read()){
		if($filename == "." || $filename == ".."){
			continue;
		}else if(is_dir("$indir/$filename") && $filename == '.svn'){
			//echo 'ooo';
			RmDirFiles("$indir/$filename");
		}else{
			rmdirsvn("$indir/$filename");
		}
	}
	$dh->close();
}

function php_alert ($message, $go = 1){
	switch ($go){
		case -1:
			echo "<script language='javascript' type='text/javascript'>alert('$message');history.go(-1);</script>";
			break;
			return ;
		case 'current':
			echo "<script language='javascript' type='text/javascript'>alert('$message');history.go(0);</script>";
			break;
			return ;
		default:
			echo "<script language='javascript' type='text/javascript'>alert('$message');window.location.href='$go';</script>";
			break;
			return ;
	}
}

/**
 * 冒泡排序取得两数组中的一个索引并用来排序,(索引值暂时为数字),数组1与数组2皆为二维数组 如array(0=>array('a'=>'a','b'=>'b'),1=>......)
 * 限制范围value不能有相同的，比如time
 * @param array $array1 数组1
 * @param string $array1_key 数组1中需要排序的索引
 * @param array $array2 数组2
 * @param string $array2_key 数组2中需要排序的索引
 * @param string $order asc/desc
 * @param int $limit 取前/后几条
 * @return array 排序好后的数组
 */
function twoarray_order($array1,$array1_key,$array2,$array2_key,$order,$limit=null){
	//首先合并两数组
	$merge_array = array_merge($array1,$array2);
	//转换成向相同的key 方便排序,
	$a = 0;
	$key = 'key';
	$tmp_array1 = array();
	$tmp_array2 = array();
	foreach ($merge_array as $row){
		if($a < count($array1)){//转换第一个数组
			$merge_array[$a][$key] = $merge_array[$a][$array1_key];
			$tmp_array1[] = $merge_array[$a][$array1_key];
			unset($merge_array[$a][$array1_key]);
		}else{
			$merge_array[$a][$key] = $merge_array[$a][$array2_key];
			unset($merge_array[$a][$array2_key]);
		}
		$a ++;
	}
	$n = count($merge_array);
	switch ($order){
		case 'asc':
			for($i = 0;$i <= $n; $i++){
				for($j = $n-2; $j >= $i; $j--){
					if($merge_array[$j][$key] > $merge_array[$j+1][$key]){
						$tmp_array = array();
						$tmp_array = $merge_array[$j+1]; 
                		$merge_array[$j+1]=$merge_array[$j]; 
                		$merge_array[$j]=$tmp_array;
					}				
				}
			}
			break;
		case 'desc':
			for($i = 0;$i <= $n; $i++){
				for($j = $n-2; $j >= $i; $j--){
					if($merge_array[$j][$key] < $merge_array[$j+1][$key]){
						$tmp_array = array();
						$tmp_array = $merge_array[$j+1]; 
                		$merge_array[$j+1]=$merge_array[$j]; 
                		$merge_array[$j]=$tmp_array;
					}				
				}
			}
			break;
		default:
			break;
			return false;
	}
	
	//将数组key转回原形
	foreach ($merge_array as $k => $v){
		if(in_array($v[$key], $tmp_array1) ){
			$merge_array[$k][$array1_key] = $v[$key];
			unset($merge_array[$k][$key]);
		}else{
			$merge_array[$k][$array2_key] = $v[$key];
			unset($merge_array[$k][$key]);
		}	
	}
	
	unset($tmp_array1,$tmp_array2,$tmp_array);
	if($limit != null){
		return array_slice($merge_array,0,intval($limit));
	}
	return $merge_array;
	
}

/**
 * 获取在线人数
 * @param string $online_log 存储的文件路径
 * @param int $timeout 超时秒数
 * @return int 返回在线总人数
 */
function get_online_num($online_log = "online.dat", $timeout = 60){
	$entries = file($online_log); //返回数组。数组中的每个单元都是文件中相应的一行
	
	$temp = array();
	
	for ($i=0;$i<count($entries);$i++) { 
	  $entry = explode(",",trim($entries[$i]));
	  if (($entry[0] != getenv('REMOTE_ADDR')) && ($entry[1] > time())) { 
	      array_push($temp,$entry[0].",".$entry[1]." "); //取出其他浏览者的信息,并去掉超时者,保存进$temp
	  } 
	} 
	
	array_push($temp,getenv('REMOTE_ADDR').",".(time() + ($timeout))." "); //更新浏览者的时间
	$users_online = count($temp); //计算在线人数
	
	$entries = implode(PHP_EOL,$temp); 
	//写入文件
	$fp = fopen($online_log,"w"); 
	flock($fp,LOCK_EX); //flock() 不能在NFS以及其他的一些网络文件系统中正常工作---要取得独占锁定(写入的程序)
	fputs($fp,$entries); 
	flock($fp,LOCK_UN); // 释放锁定
	fclose($fp); 
	unset($online_log,$timeout,$entries,$temp);
	return $users_online;
}

/**
 * 形式：127.0.0.1,1259687459,100.分别为ip,时间,人数
 * @param string $visit_log 存储的文件名
 * @param int $timeout 多长时间内刷不算
 * @param int $save_num 文件存储的最长行数
 * @return int 总访问人数 
 */
function get_visit_num($visit_log = "visit_num.dat", $timeout = 60, $save_num = 100){
	$entries = file($visit_log); //返回数组。数组中的每个单元都是文件中相应的一行
	$visits = is_array($entries) ? end($entries) : '1,1,1';
	$visit_arr = explode(",",trim($visits));
	$visit_num = $visit_arr[2];//得到当时总访问人数
	$temp = array();
	
	for ($i=0;$i<count($entries);$i++) { 
		$entry = explode(",",trim($entries[$i]));
		if($entry[0] == getenv('REMOTE_ADDR') && $entry[1] > time()){
			return $visit_num;
		}else if ($entry[0] != getenv('REMOTE_ADDR')) { 
		  array_push($temp,$entry[0].",".$entry[1].",".$entry[2]);   
		}else if($entry[0] == getenv('REMOTE_ADDR') && $entry[1] < time()){
			continue;
		}
	}
	array_push($temp,getenv('REMOTE_ADDR').",".(time() + ($timeout)).",".($visit_num+1)); //添加浏览者
	if(count($temp) > $save_num){
		unset($temp[0]);
	}
	$entries = implode(PHP_EOL,$temp);
	//更新文件
	$fp = fopen($visit_log,"w"); 
	flock($fp,LOCK_EX); //flock() 不能在NFS以及其他的一些网络文件系统中正常工作---要取得独占锁定(写入的程序)
	fputs($fp,$entries); 
	flock($fp,LOCK_UN); // 释放锁定
	fclose($fp);
	unset($visit_log,$timeout,$save_num,$entries,$visits,$visit_arr,$temp);
	return ($visit_num+1);
}

//去除某些htm标签，避免影响css样式
function remove_html_tag($str, $arr = array("div","span")){
	$str = preg_replace(array("/\<div[^\/]*\>/i","/\<span[^\/]*\>/i"),array("",""),$str);
	$str = str_replace(array("<div","<span","</div>","</span>"),array("",""),$str);
	return $str;
}

function http_request($url, $params = array(), $method = 'GET', &$error = null)
{
	$ch = curl_init();
    if (strtoupper($method) == 'GET') {
        curl_setopt($ch, CURLOPT_POST, false);
        if ($params) {
            if (strstr($url,'?')) {
	        	$url .= '&'.http_build_query($params);
	        } else {
	        	$url .= '?'.http_build_query($params);
	        }
        }
    } else {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    }
    curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HEADER, false);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$response = curl_exec($ch);
	if ($response === false && !is_null($error)) {
		$error = curl_errno($ch).' '.curl_error($ch);
	}
	curl_close($ch);
	return $response;
}

?>